<template>
  <div>
    <el-dialog
      width="400px"
      :title="title"
      :visible.sync="checkVisible"
      @close="onClose"
    >
      <el-tabs v-model="activeName" type="border-card" @tab-click="tabClick">
        <!--
          @treeNodeCheck="treeNodeCheck1"
          :tree-default-checked-keys="checkedKey" -->
        <el-tab-pane label="选择用户" name="选择用户">
          <compTree
            ref="selectUserTree"
            :show-search="false"
            :tree-show-checkbox="true"
            :tree-data="userData"
            :tree-height="300"
            :tree-default-checked-keys="treeDefaultCheckedKeys"
            :tree-default-expanded-keys="userExpandedKey"
            @treeNodeCheck="treeNodeCheck1"
          />
        </el-tab-pane>
        <el-tab-pane label="选择方案" name="选择方案">
          <compTree
            ref="selectUserTree"
            :show-search="false"
            :tree-show-checkbox="true"
            :tree-data="planData"
            :tree-height="300"
            :tree-default-checked-keys="treeDefaultCheckedKeys2"
            :tree-default-expanded-keys="planExpandedKey"
            @treeNodeCheck="treeNodeCheck2"
          />
        </el-tab-pane>
      </el-tabs>
      <div style="height:20px">
        <el-checkbox v-show="isShow" v-model="returnNameChecked" style="margin-top:10px">
          <span style="color: black">返回用户名</span><span style="color: blue">(微信发送为必选)</span>
        </el-checkbox>
      </div>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button v-show="isShow" style="float: left" type="primary" @click="saveUserPlan">另存为方案</el-button>
        <el-button
          size="mini"
          @click="dialogClose"
        >取 消</el-button>
        <el-button
          size="mini"
          type="primary"
          @click="dialogConfirm"
        >确 定</el-button>
      </span>
    </el-dialog>
    <show-plan-config-name-layer ref="showPlanConfigNameLayer" :params="paramsObj" />
  </div>
</template>
<script>
import { getUserList, getPlanList } from '@/api/event'
import { addPlanInfo } from '@/api/user'
import { ParamArr, SQLTable } from '@/../public/js/paramarr'
import Global from '@/../public/js/global'
import ShowPlanConfigNameLayer from '@/components/Dialog/ShowPlanConfigNameLayer.vue'

export default {
  name: 'SelectUserPlanLayerDialog',
  components: {
    ShowPlanConfigNameLayer
  },
  props: {
    // eslint-disable-next-line vue/require-default-prop
    params: {
      type: Object
    },
    title: {
      type: String,
      default: '选择用户'
    },
    width: {
      type: String,
      default: '70%'
    }
  },
  data() {
    return {
      checked: false,
      checkVisible: false,
      returnNameChecked: false,
      formData: {},
      //   表格数据
      formDatas: {
        prot: '',
        user: '',
        pass: ''
      },
      paramsObj: {},
      userData: [],
      planData: [],
      // 默认选择的多选框
      treeDefaultCheckedKeys: [],
      treeDefaultCheckedKeys2: [],
      treeUserID1: [],
      treeUserID2: [],
      userExpandedKey: [],
      planExpandedKey: [],
      // 选中的标签栏
      activeName: '选择用户',
      isShow: true,
      // 树1选中的数组
      treeData1: [],
      treeDataID1: [],
      treeDataUserid1: [],
      // 树2选中的数组
      treeData2: [],
      treeDataID2: [],
      treeDataUserid2: []

    }
  },
  watch: {

  },
  Create() {
    this.open()
  },
  methods: {
    open(ok) {
      this.formData = this._.cloneDeep(this.params)
      this.ok = ok
      this.checkVisible = true
      // 勾选返回用户名
      // if (this.formData[0].type === 2 || this.formData[0].type === 3) {

      // this.returnNameChecked = true
      // }
      getUserList(new ParamArr()).then(vPar => {
        var nodes = []
        var nodeMap = new Map()
        // 分组
        var table = new SQLTable(vPar.getTable('QryGroup'))
        table.first()
        while (!table.eof()) {
          var node = {}
          node['id'] = table.getValueByName('ID')
          node.pid = table.getValueByName('PID')
          node['loginid'] = node.id
          node['name'] = table.getValueByName('Name')
          node['text'] = node['text'] = node['name']
          node['icon'] = 'folder'
          node.folder = true
          const pnode = Global.getTreeviewPNode(nodeMap, nodes, node.pid)
          pnode.push(node)
          nodeMap.set(node.id, node)
          table.next()
        }
        // 用户
        table = new SQLTable(vPar.getTable('QryUser'))
        // const cArr = (g_initData.sID || '').split(',')
        table.first()
        while (!table.eof()) {
          const node = {}
          node.id = table.getValueByName('ID')
          node.pid = table.getValueByName('PID')
          node['text'] = table.getValueByName('UserName')
          node['name'] = table.getValueByName('UserName')
          node['loginid'] = node.id
          node['userid'] = table.getValueByName('UserID')
          node['mail'] = table.getValueByName('EMail')
          node['mobile'] = table.getValueByName('Mobile')
          node['folder'] = false
          node['icon'] = 'user'
          node.state = {}
          if (this.formData[0].name !== '' && this.formData[0].name !== undefined) {
            this.formData[0].name.split(',').forEach(element => {
              if (node.name === element) {
                this.treeDefaultCheckedKeys.push(node.id)
                this.userExpandedKey.push(node.pid)
              }
            })
          }
          if (this.formData[0].sID !== '' && this.formData[0].sID !== undefined) {
            this.formData[0].sID.replace(/(\[方案\])|(\{流程执行用户\})/g, '').split(',').forEach(element => {
              if (node.userid === element) {
                this.treeDefaultCheckedKeys.push(node.id)
                this.userExpandedKey.push(node.pid)
              }
            })
          }
          const pnode = Global.getTreeviewPNode(nodeMap, nodes, node.pid)
          pnode.push(node)
          nodeMap.set(node.id, node)
          table.next()
        }
        this.userData = nodes
      })
      getPlanList(new ParamArr()).then(vPar => {
        this.initPlan(vPar)
        if (this.treeDefaultCheckedKeys2.length > 0) {
          this.activeName = '选择方案'
          this.isShow = false
        } else {
          this.activeName = '选择用户'
          this.isShow = true
          this.returnNameChecked = true
        }
      })
    },
    treeNodeCheck1(a, b) {
      this.treeData1 = []
      this.treeDataID1 = []
      this.treeDataUserid1 = []
      b.checkedNodes.forEach(element => {
        if (element.icon !== 'folder') {
          this.treeData1.push(element.name)
          this.treeDataID1.push(element.id)
          this.treeDataUserid1.push(element.userid)
        }
      })
    },
    treeNodeCheck2(a, b) {
      this.treeData2 = []
      this.treeDataID2 = []
      this.treeDataUserid2 = []
      b.checkedNodes.forEach(element => {
        if (element.icon !== 'folder') {
          this.treeData2.push(element.name)
          this.treeDataID2.push(element.id)
          this.treeDataUserid2.push(element.id)
        }
      })
    },
    onClose() {
      this.ok()
    },
    initPlan(vPar) {
      // this.$forceUpdate()
      const nodes = []
      const table = new SQLTable(vPar.getTable('k_target_plan'))
      const nodeMap = new Map()
      table.first()
      while (!table.eof()) {
        const node = {}
        node['id'] = table.getValueByName('ID')
        node['pid'] = table.getValueByName('PID')
        node['name'] = table.getValueByName('Name')
        if (table.getValueByName('Type') === '0') {
          node['icon'] = 'folder'
          node['text'] = node.name
        } else {
          node['icon'] = 'user'
          node['text'] = node.name
        }
        node.state = {}
        if (this.formData[0].name !== '' && this.formData[0].name !== undefined) {
          const idArr = this.formData[0].name.replace(/(\[方案\])|(\{流程执行用户\})/g, '').split(',')
          idArr.forEach(element => {
            if (node.name === element) {
              this.treeDefaultCheckedKeys2.push(node.id)
              this.planExpandedKey.push(node.pid)
            }
          })
        }
        if (this.formData[0].sID !== '' && this.formData[0].sID !== undefined) {
          this.formData[0].sID.replace(/(\[方案\])|(\{流程执行用户\})/g, '').split(',').forEach(element => {
            if (node.id === element) {
              this.treeDefaultCheckedKeys2.push(node.id)
              this.planExpandedKey.push(node.pid)
            }
          })
        }
        const pnode = Global.getTreeviewPNode(nodeMap, nodes, node['pid'])
        pnode.push(node)
        nodeMap.set(node['id'], node)
        table.next()
      }
      this.planData = nodes
    },
    saveUserPlan() {
      if (this.treeData1.length === 0) {
        this.$message({
          type: 'warning',
          message: '请选择用户!'
        })
        return
      }
      this.$set(this.paramsObj, 0, true)
      this.$refs.showPlanConfigNameLayer.open((res) => {
        this.planData.push({ text: res.sNames, icon: 'user' })
        var vPar = new ParamArr()
        vPar.setStr('LoginIDs', this.treeDataID1)
        vPar.setStr('LoginNames', this.treeData1)
        vPar.setStr('Name', res.sNames)
        vPar.setBool('Enable', true)
        vPar.setBool('NoMsg', res.isMsg)
        vPar.setBool('NoWeChat', res.isWeChat)
        addPlanInfo(vPar).then((vPar) => {
          getPlanList(vPar).then()
        })
      })
    },
    tabClick() {
      if (this.activeName === '选择方案') {
        this.isShow = false
      } else {
        this.isShow = true
      }
    },
    dialogClose() {
      this.checkVisible = false
      this.ok()
    },
    dialogConfirm() {
      if ((this.treeData1.length > 0 && this.treeDefaultCheckedKeys2.length > 0) || (this.treeData2.length > 0 && this.treeDefaultCheckedKeys.length > 0)) {
        this.ok('')
      } else if (this.treeData1.length > 0) {
        this.ok({ name: this.treeData1.toString(), ids: this.treeDataID1, userid: this.treeDataUserid1 })
      } else if (this.treeData2.length > 0) {
        const a = '[方案]'
        this.ok({ name: a + this.treeData2.toString(), ids: a + this.treeDataID2, userid: a + this.treeDataUserid2 })
      }
      this.checkVisible = false
    }
  }
}
</script>
